<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售员" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入销售员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称"  >
        <el-input
          v-model="queryParams.params.materialName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="销售部门" prop="deptId" style="margin-left: 10px">-->
<!--        <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择销售部门" style="width: 240px" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="物流单号" prop="logisticsNumber"  >-->
<!--        <el-input-->
<!--          v-model="queryParams.logisticsNumber"-->
<!--          placeholder="请输入物流单号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="销售日期"  style="margin-left: 10px" >
        <el-date-picker
          v-model="queryParams.saleDateQuery"
          type="daterange"
          unlink-panels
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item style="margin-left: 20px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['sale:saleOrder:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['sale:saleOrder:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['sale:saleOrder:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--   标准计划排产    -->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="workOrderPreview"-->
<!--          :disabled="multiple"-->
<!--        >计划排产</el-button>-->
<!--      </el-col>-->
      <!--   全手工计划排产    -->
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="openProcessPlan"
          :disabled="multiple"
        >工序排产</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleOrderList" @selection-change="handleSelectionChange"  >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售日期" align="center" prop="salOrder.saleDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.salOrder.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="salOrder.customerName" width="150"/>
      <el-table-column label="合同编号" align="center" prop="salOrder.number" width="80"/>
      <el-table-column label="产品" align="center" prop="materialName"width="100" />
      <el-table-column label="规格型号" align="center" prop="materialSpecification" />
      <!--   天润项目自定义字段   -->
      <el-table-column label="粘度" align="center"  width="100">
        <template slot-scope="scope">
          <span> {{scope.row.extendFieldJson.viscosity}}</span>
        </template>
      </el-table-column>

      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="状态" align="center" prop="status" >
        <template v-slot="scope">
          <dict-tag :options="dict.type.salorder_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="180"/>
      <el-table-column label="发货日期" align="center" prop="deliveryDate" />

<!--  生产部分不应显示金额    <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="金额" align="center" prop="totalPrice" />
      <el-table-column label="销售部门" align="center" prop="salOrder.deptName" />
      <el-table-column label="产品编号" align="center" prop="materialNumber" />
      <el-table-column label="销售员" align="center" prop="salOrder.userName" />
      -->
    <!--  显示扩展字段    -->
      <div v-for="(item,index) in entryFieldExtendList">
          <!--  天润项目中使用，粘度字段位置不能在最后        -->
          <div  v-if="item.fieldName!='粘度'">
          <el-table-column :label="item.fieldName" align="center"  >
            <template slot-scope="scope">
              <span> {{scope.row.extendFieldJson[item.field]}}</span>
            </template>
          </el-table-column>
          </div>
      </div>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.mainId)"
            v-hasPermi="['sale:saleOrder:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sale:saleOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog title="选择工序" :visible.sync="dialogFormVisible">

      <el-select v-model="queryParams.processId" placeholder="请选择">
        <el-option
          v-for="item in processList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="workOrderPreview">确 定</el-button>
      </div>
    </el-dialog>

  </div>


</template>

<script>
import { listSaleOrder, delSaleOrder } from "@/api/mes/sale/saleOrder";
import { deptTreeSelect } from '@/api/system/user'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MaterialSelect  from "@/components/mes/materialSelect.vue";
import { listFieldExtend } from "@/api/mes/system/fieldExtend";
import { listProcess } from "@/api/mes/production/process";
export default {
  name: "SaleOrder",
  components: { Treeselect,MaterialSelect },
  dicts: ['salorder_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      entryIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单表格数据
      saleOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: null,
        status: null,
        logisticsNumber: null,
        deptId:null,
        deptName: null,
        userName: null,
        saleDateQuery:[],
        customerName: null,
        params:{
          materialName:null,
        }
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "本周",
            onClick(picker) {
              // 获取今天
              const end = new Date();
              // 获取当前周的第一天
              const start = new Date(
                end.getFullYear(),
                end.getMonth(),
                end.getDate() - ((end.getDay() + 6) % 7)
              );
              start.setTime(start.getTime());
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本月",
            onClick(picker) {
              const end = new Date();
              // 获取当前月的第一天
              const start = new Date(end.getFullYear(), end.getMonth(), 1);
              start.setTime(start.getTime());
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本年",
            onClick(picker) {
              const end = new Date();
              // 获取当前年的第一天
              const start = new Date(end.getFullYear(), 0, 1);
              start.setTime(start.getTime());
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上一年",
            onClick(picker) {
              const now = new Date();
              // 获取当前年的第一天
              const start = new Date(now.getFullYear()-1, 0, 1);
              const end = new Date(now.getFullYear()-1, 11, 31);
              start.setTime(start.getTime());
              picker.$emit("pick", [start, end]);
            },
          },
        ]
      },
      // 部门树选项
      deptOptions: undefined,
      entryFieldExtendList:{},
      dialogFormVisible: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      processList :[],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询销售订单列表 */
    getList() {
      this.loading = true;

      //获取销售订单子表扩展字段结构
      listFieldExtend({pageSize: 99999,sourceBill:'saleOrderEntry'}).then(response => {
        this.entryFieldExtendList = response.rows;
        this.loading = false;
      });


      listSaleOrder(this.queryParams).then(response => {
        this.saleOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {

      this.ids = selection.map(item => item.mainId);
      this.entryIds=selection.map(item => item.id);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: "/mes/saleOrder-add/index" });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row
      this.$router.push({ path: "/mes/saleOrder-edit/index/"+id });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.mainId || this.ids;
      this.$modal.confirm('此动作将删除整张单据，请确认!!!').then(function() {
        return delSaleOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('sale/saleOrder/export', {
        ...this.queryParams
      }, `saleOrder_${new Date().getTime()}.xlsx`)
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <=2 || columnIndex >=10) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 标准半自动排产
    // workOrderPreview(){
    //   //二次确认弹框
    //   this.$modal.confirm('排产计划保存后会生成工单，请仔细核对数据，若有未完成计划请先保存。', '提示', {
    //     confirmButtonText: '确定',
    //     type: 'warning'
    //   }).then(() => {
    //     this.$router.push({name: "workOrderPreview", params: {"ids": this.entryIds.join(),"billType":"saleOrder"}})
    //   })
    // }
    //纯手工排产
    workOrderPreview(){
      let processId =this.queryParams.processId;
      if(typeof(processId)==="undefined"){
        this.$modal.msgWarning("请选择工序");
        return;
      }
      this.dialogFormVisible=false;
      //跳转排产页面
      this.$router.push({name: "workOrderPreviewA", params: {"ids": this.entryIds.join(),"billType":"saleOrder","processId":processId}})

    },
    openProcessPlan(){

      listProcess({pageNum: 1,pageSize: 999999 ,status: '0'} ).then(response => {
        this.processList = response.rows;
      });
      this.dialogFormVisible=true;
    }

  }
};
</script>
